//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package admin_auth_user_api_serv

import (
	"context"
	"time"

	"atomgit.com/openlinksaas-org/api-server/admin_api_serv/admin_common"
	"atomgit.com/openlinksaas-org/api-server/config"
	"atomgit.com/openlinksaas-org/api-server/dao"
	"atomgit.com/openlinksaas-org/proto-gen-go.git/admin_auth_api"
	"go.mongodb.org/mongo-driver/mongo"
	"google.golang.org/protobuf/proto"
)

type AdminAuthAdminApiImpl struct {
	admin_auth_api.UnimplementedAdminAuthAdminApiServer
	adminCfg *config.AdminCfg
}

func NewAdminAuthAdminApiImpl(adminCfg *config.AdminCfg) *AdminAuthAdminApiImpl {
	return &AdminAuthAdminApiImpl{adminCfg: adminCfg}
}

func (apiImpl *AdminAuthAdminApiImpl) AddUser(ctx context.Context, req *admin_auth_api.AdminAddUserRequest) (*admin_auth_api.AdminAddUserResponse, error) {
	sess, ok := dao.CacheDao.GetAdminSession(ctx, req.AdminSessionId)
	if !ok {
		return &admin_auth_api.AdminAddUserResponse{
			Code:   admin_auth_api.AdminAddUserResponse_CODE_WRONG_SESSION,
			ErrMsg: "会话不存在",
		}, nil
	}
	if !sess.AuthOk {
		return &admin_auth_api.AdminAddUserResponse{
			Code:   admin_auth_api.AdminAddUserResponse_CODE_NOT_AUTH,
			ErrMsg: "未授权会话",
		}, nil
	}
	adminUserCfg, err := admin_common.GetAdminUserConfig(ctx, apiImpl.adminCfg, sess.UserName)
	if err != nil {
		return nil, err
	}
	if !adminUserCfg.PermInfo.SuperAdminUser {
		return &admin_auth_api.AdminAddUserResponse{
			Code:   admin_auth_api.AdminAddUserResponse_CODE_NO_PERMISSION,
			ErrMsg: "没有权限",
		}, nil
	}
	//检测目前用户是否存在
	if req.UserName == apiImpl.adminCfg.SuperUser {
		return &admin_auth_api.AdminAddUserResponse{
			Code:   admin_auth_api.AdminAddUserResponse_CODE_USER_EXIST,
			ErrMsg: "用户已存在",
		}, nil
	}
	exist, err := dao.AdminUserDao.Exist(ctx, req.UserName)
	if err != nil {
		return nil, err
	}
	if exist {
		return &admin_auth_api.AdminAddUserResponse{
			Code:   admin_auth_api.AdminAddUserResponse_CODE_USER_EXIST,
			ErrMsg: "用户已存在",
		}, nil
	}

	req.PermInfo.SuperAdminUser = false
	permInfoData, err := proto.Marshal(req.PermInfo)
	if err != nil {
		return nil, err
	}

	nowTime := time.Now().UnixNano() / 1e6

	dbSess, err := dao.StartSession()
	if err != nil {
		return nil, err
	}
	defer dao.EndSession(dbSess)

	ret, err := dbSess.WithTransaction(ctx, func(sessCtx mongo.SessionContext) (interface{}, error) {
		err = dao.AdminUserDao.Insert(sessCtx, &dao.AdminUserInfoDbItem{
			UserName:     req.UserName,
			UserDesc:     req.UserDesc,
			PubKey:       req.PubKey,
			PermInfoData: permInfoData,
			TimeStamp:    nowTime,
		})
		if err != nil {
			return nil, err
		}
		return &admin_auth_api.AdminAddUserResponse{
			Code: admin_auth_api.AdminAddUserResponse_CODE_OK,
		}, nil
	})
	if err != nil {
		return nil, err
	}
	return ret.(*admin_auth_api.AdminAddUserResponse), nil
}

func (apiImpl *AdminAuthAdminApiImpl) UpdateUserPubKey(ctx context.Context, req *admin_auth_api.AdminUpdateUserPubKeyRequest) (*admin_auth_api.AdminUpdateUserPubKeyResponse, error) {
	sess, ok := dao.CacheDao.GetAdminSession(ctx, req.AdminSessionId)
	if !ok {
		return &admin_auth_api.AdminUpdateUserPubKeyResponse{
			Code:   admin_auth_api.AdminUpdateUserPubKeyResponse_CODE_WRONG_SESSION,
			ErrMsg: "会话不存在",
		}, nil
	}
	if !sess.AuthOk {
		return &admin_auth_api.AdminUpdateUserPubKeyResponse{
			Code:   admin_auth_api.AdminUpdateUserPubKeyResponse_CODE_NOT_AUTH,
			ErrMsg: "未授权会话",
		}, nil
	}
	adminUserCfg, err := admin_common.GetAdminUserConfig(ctx, apiImpl.adminCfg, sess.UserName)
	if err != nil {
		return nil, err
	}
	if !adminUserCfg.PermInfo.SuperAdminUser {
		return &admin_auth_api.AdminUpdateUserPubKeyResponse{
			Code:   admin_auth_api.AdminUpdateUserPubKeyResponse_CODE_NO_PERMISSION,
			ErrMsg: "没有权限",
		}, nil
	}

	dbSess, err := dao.StartSession()
	if err != nil {
		return nil, err
	}
	defer dao.EndSession(dbSess)

	ret, err := dbSess.WithTransaction(ctx, func(sessCtx mongo.SessionContext) (interface{}, error) {
		err = dao.AdminUserDao.UpdatePubKey(sessCtx, req.UserName, req.PubKey)
		if err != nil {
			return nil, err
		}
		return &admin_auth_api.AdminUpdateUserPubKeyResponse{
			Code: admin_auth_api.AdminUpdateUserPubKeyResponse_CODE_OK,
		}, nil
	})
	if err != nil {
		return nil, err
	}
	return ret.(*admin_auth_api.AdminUpdateUserPubKeyResponse), nil
}

func (apiImpl *AdminAuthAdminApiImpl) UpdateUserPerm(ctx context.Context, req *admin_auth_api.AdminUpdateUserPermRequest) (*admin_auth_api.AdminUpdateUserPermResponse, error) {
	sess, ok := dao.CacheDao.GetAdminSession(ctx, req.AdminSessionId)
	if !ok {
		return &admin_auth_api.AdminUpdateUserPermResponse{
			Code:   admin_auth_api.AdminUpdateUserPermResponse_CODE_WRONG_SESSION,
			ErrMsg: "会话不存在",
		}, nil
	}
	if !sess.AuthOk {
		return &admin_auth_api.AdminUpdateUserPermResponse{
			Code:   admin_auth_api.AdminUpdateUserPermResponse_CODE_NOT_AUTH,
			ErrMsg: "未授权会话",
		}, nil
	}
	adminUserCfg, err := admin_common.GetAdminUserConfig(ctx, apiImpl.adminCfg, sess.UserName)
	if err != nil {
		return nil, err
	}
	if !adminUserCfg.PermInfo.SuperAdminUser {
		return &admin_auth_api.AdminUpdateUserPermResponse{
			Code:   admin_auth_api.AdminUpdateUserPermResponse_CODE_NO_PERMISSION,
			ErrMsg: "没有权限",
		}, nil
	}

	req.PermInfo.SuperAdminUser = false
	permInfoData, err := proto.Marshal(req.PermInfo)
	if err != nil {
		return nil, err
	}

	dbSess, err := dao.StartSession()
	if err != nil {
		return nil, err
	}
	defer dao.EndSession(dbSess)

	ret, err := dbSess.WithTransaction(ctx, func(sessCtx mongo.SessionContext) (interface{}, error) {
		err = dao.AdminUserDao.UpdatePerm(sessCtx, req.UserName, permInfoData)
		if err != nil {
			return nil, err
		}
		return &admin_auth_api.AdminUpdateUserPermResponse{
			Code: admin_auth_api.AdminUpdateUserPermResponse_CODE_OK,
		}, nil
	})
	if err != nil {
		return nil, err
	}
	return ret.(*admin_auth_api.AdminUpdateUserPermResponse), nil
}

func (apiImpl *AdminAuthAdminApiImpl) UpdateUserDesc(ctx context.Context, req *admin_auth_api.AdminUpdateUserDescRequest) (*admin_auth_api.AdminUpdateUserDescResponse, error) {
	sess, ok := dao.CacheDao.GetAdminSession(ctx, req.AdminSessionId)
	if !ok {
		return &admin_auth_api.AdminUpdateUserDescResponse{
			Code:   admin_auth_api.AdminUpdateUserDescResponse_CODE_WRONG_SESSION,
			ErrMsg: "会话不存在",
		}, nil
	}
	if !sess.AuthOk {
		return &admin_auth_api.AdminUpdateUserDescResponse{
			Code:   admin_auth_api.AdminUpdateUserDescResponse_CODE_NOT_AUTH,
			ErrMsg: "未授权会话",
		}, nil
	}
	adminUserCfg, err := admin_common.GetAdminUserConfig(ctx, apiImpl.adminCfg, sess.UserName)
	if err != nil {
		return nil, err
	}
	if !adminUserCfg.PermInfo.SuperAdminUser {
		return &admin_auth_api.AdminUpdateUserDescResponse{
			Code:   admin_auth_api.AdminUpdateUserDescResponse_CODE_NO_PERMISSION,
			ErrMsg: "没有权限",
		}, nil
	}

	dbSess, err := dao.StartSession()
	if err != nil {
		return nil, err
	}
	defer dao.EndSession(dbSess)

	ret, err := dbSess.WithTransaction(ctx, func(sessCtx mongo.SessionContext) (interface{}, error) {
		err = dao.AdminUserDao.UpdateUserDesc(sessCtx, req.UserName, req.UserDesc)
		if err != nil {
			return nil, err
		}
		return &admin_auth_api.AdminUpdateUserDescResponse{
			Code: admin_auth_api.AdminUpdateUserDescResponse_CODE_OK,
		}, nil
	})
	if err != nil {
		return nil, err
	}
	return ret.(*admin_auth_api.AdminUpdateUserDescResponse), nil
}

func (apiImpl *AdminAuthAdminApiImpl) ListUser(ctx context.Context, req *admin_auth_api.AdminListUserRequest) (*admin_auth_api.AdminListUserResponse, error) {
	emptyList := []*admin_auth_api.AdminUserInfo{}

	sess, ok := dao.CacheDao.GetAdminSession(ctx, req.AdminSessionId)
	if !ok {
		return &admin_auth_api.AdminListUserResponse{
			Code:          admin_auth_api.AdminListUserResponse_CODE_WRONG_SESSION,
			ErrMsg:        "会话不存在",
			AdminUserList: emptyList,
		}, nil
	}
	if !sess.AuthOk {
		return &admin_auth_api.AdminListUserResponse{
			Code:          admin_auth_api.AdminListUserResponse_CODE_NOT_AUTH,
			ErrMsg:        "未授权会话",
			AdminUserList: emptyList,
		}, nil
	}
	adminUserCfg, err := admin_common.GetAdminUserConfig(ctx, apiImpl.adminCfg, sess.UserName)
	if err != nil {
		return nil, err
	}
	if !adminUserCfg.PermInfo.SuperAdminUser {
		return &admin_auth_api.AdminListUserResponse{
			Code:          admin_auth_api.AdminListUserResponse_CODE_NO_PERMISSION,
			ErrMsg:        "没有权限",
			AdminUserList: emptyList,
		}, nil
	}

	count, err := dao.AdminUserDao.Count(ctx)
	if err != nil {
		return nil, err
	}
	userItemList, err := dao.AdminUserDao.List(ctx, int64(req.Offset), int64(req.Limit))
	if err != nil {
		return nil, err
	}
	userList := []*admin_auth_api.AdminUserInfo{}
	for _, userItem := range userItemList {
		user, err := userItem.ToAdminUserInfo()
		if err != nil {
			continue
		}
		userList = append(userList, user)
	}
	return &admin_auth_api.AdminListUserResponse{
		Code:          admin_auth_api.AdminListUserResponse_CODE_OK,
		TotalCount:    count,
		AdminUserList: userList,
	}, nil
}

func (apiImpl *AdminAuthAdminApiImpl) GetUser(ctx context.Context, req *admin_auth_api.AdminGetUserRequest) (*admin_auth_api.AdminGetUserResponse, error) {
	emptyInfo := &admin_auth_api.AdminUserInfo{
		PermInfo: &admin_auth_api.AdminPermInfo{
			UserPerm:          &admin_auth_api.UserPerm{},
			ProjectPerm:       &admin_auth_api.ProjectPerm{},
			ProjectMemberPerm: &admin_auth_api.ProjectMemberPerm{},
			MenuPerm:          &admin_auth_api.MenuPerm{},
			AppStorePerm:      &admin_auth_api.AppStorePerm{},
			IdeaStorePerm:     &admin_auth_api.IdeaStorePerm{},
			WidgetStorePerm:   &admin_auth_api.WidgetStorePerm{},
			SwStorePerm:       &admin_auth_api.SwStorePerm{},
			OrgPerm:           &admin_auth_api.OrgPerm{},
			OrgMemberPerm:     &admin_auth_api.OrgMemberPerm{},
			KeywordPerm:       &admin_auth_api.KeywordPerm{},
		},
	}

	sess, ok := dao.CacheDao.GetAdminSession(ctx, req.AdminSessionId)
	if !ok {
		return &admin_auth_api.AdminGetUserResponse{
			Code:      admin_auth_api.AdminGetUserResponse_CODE_WRONG_SESSION,
			ErrMsg:    "会话不存在",
			AdminUser: emptyInfo,
		}, nil
	}
	if !sess.AuthOk {
		return &admin_auth_api.AdminGetUserResponse{
			Code:      admin_auth_api.AdminGetUserResponse_CODE_NOT_AUTH,
			ErrMsg:    "未授权会话",
			AdminUser: emptyInfo,
		}, nil
	}
	adminUserCfg, err := admin_common.GetAdminUserConfig(ctx, apiImpl.adminCfg, sess.UserName)
	if err != nil {
		return nil, err
	}
	if !adminUserCfg.PermInfo.SuperAdminUser {
		return &admin_auth_api.AdminGetUserResponse{
			Code:      admin_auth_api.AdminGetUserResponse_CODE_NO_PERMISSION,
			ErrMsg:    "没有权限",
			AdminUser: emptyInfo,
		}, nil
	}

	userItem, err := dao.AdminUserDao.Get(ctx, req.UserName)
	if err != nil {
		return &admin_auth_api.AdminGetUserResponse{
			Code:      admin_auth_api.AdminGetUserResponse_CODE_NO_USER,
			ErrMsg:    "用户不存在",
			AdminUser: emptyInfo,
		}, nil
	}
	user, err := userItem.ToAdminUserInfo()
	if err != nil {
		return nil, err
	}
	return &admin_auth_api.AdminGetUserResponse{
		Code:      admin_auth_api.AdminGetUserResponse_CODE_OK,
		AdminUser: user,
	}, nil
}

func (apiImpl *AdminAuthAdminApiImpl) RemoveUser(ctx context.Context, req *admin_auth_api.AdminRemoveUserRequest) (*admin_auth_api.AdminRemoveUserResponse, error) {
	sess, ok := dao.CacheDao.GetAdminSession(ctx, req.AdminSessionId)
	if !ok {
		return &admin_auth_api.AdminRemoveUserResponse{
			Code:   admin_auth_api.AdminRemoveUserResponse_CODE_WRONG_SESSION,
			ErrMsg: "会话不存在",
		}, nil
	}
	if !sess.AuthOk {
		return &admin_auth_api.AdminRemoveUserResponse{
			Code:   admin_auth_api.AdminRemoveUserResponse_CODE_NOT_AUTH,
			ErrMsg: "未授权会话",
		}, nil
	}
	adminUserCfg, err := admin_common.GetAdminUserConfig(ctx, apiImpl.adminCfg, sess.UserName)
	if err != nil {
		return nil, err
	}
	if !adminUserCfg.PermInfo.SuperAdminUser {
		return &admin_auth_api.AdminRemoveUserResponse{
			Code:   admin_auth_api.AdminRemoveUserResponse_CODE_NO_PERMISSION,
			ErrMsg: "没有权限",
		}, nil
	}

	dbSess, err := dao.StartSession()
	if err != nil {
		return nil, err
	}
	defer dao.EndSession(dbSess)

	ret, err := dbSess.WithTransaction(ctx, func(sessCtx mongo.SessionContext) (interface{}, error) {
		err = dao.AdminUserDao.Remove(sessCtx, req.UserName)
		if err != nil {
			return nil, err
		}
		return &admin_auth_api.AdminRemoveUserResponse{
			Code: admin_auth_api.AdminRemoveUserResponse_CODE_OK,
		}, nil
	})
	if err != nil {
		return nil, err
	}
	return ret.(*admin_auth_api.AdminRemoveUserResponse), nil
}
